package com.fyzk.activity.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.fyzk.activity.app.ActivityTaskManager;
import com.fyzk.activity.lottery.basketball.JCLQFragmentActivityI;
import com.fyzk.activity.lottery.jc.football.newJz.FootballFragmentActivityI;
import com.fyzk.activity.lottery.recommend_order.MyBaskOrderActivity;
import com.fyzk.activity.lottery.recommend_order.MyBaskOrderAdapter;
import com.fyzk.activity.lottery.recommend_order.MyRecommendBean;
import com.fyzk.activity.lottery.recommend_order.MyRecommendOrderBean;
import com.fyzk.activity.lottery.recommend_order.RecommendHelpActivity;
import com.fyzk.activity.user.LoginActivity;
import com.fyzk.base.BaseFragment;
import com.fyzk.data.AppLotteryInfos;
import com.fyzk.data.preference.MySharedPreferences;
import com.fyzk.net.Commands;
import com.fyzk.view.DynamicLoadListener;
import com.fyzk.view.TopTitleView;
import com.fyzk.view.ViewCallBack;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.OnRefreshListener;
import com.tyjc.lottery.R;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import http.Common.CommandUtil;
import http.StringResultBean;

/**
 * <p>
 *
 * @author Administrator
 * @mood
 * @description 晒单
 * @date 2018/8/4 14:13
 * </p>
 */
public class BaskOrderFragment extends BaseFragment implements OnRefreshListener, DynamicLoadListener {
    private View mainView;
    private TopTitleView topView;

    public static boolean isRecommendOrder = false;
    private RecyclerView mListview;
    private int type = 0;   // 类型（荐单：0；跟单：1）
    private int page = 0;
    private int count = 20;
    private List<MyRecommendOrderBean> infos = new ArrayList<>();
    private MyBaskOrderAdapter adapter;
    private SmartRefreshLayout mRefreshLayout;
    private boolean isFirst = true;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.fragment_bask_order, null);
        initView();
        return mainView;
    }

    private void initView() {
        topView = mainView.findViewById(R.id.recommendorder_topview);
        topView.getRl().setMinimumHeight(150);
        topView.getRl().setPadding(0, 50, 0, 0);
        topView.setOnTitleClickListener(this);
        mListview = mainView.findViewById(R.id.listview);
        mListview.setLayoutManager(new LinearLayoutManager(getContext()));
        mRefreshLayout = mainView.findViewById(R.id.refreshlayout);
        mRefreshLayout.setOnRefreshListener(this);
        adapter = new MyBaskOrderAdapter(getContext(), infos, this);
        mListview.setAdapter(adapter);

        onRefresh(mRefreshLayout);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden){
            onRefresh(mRefreshLayout);
        }
    }

    @Override
    public void onClick(View arg0) {
        switch (arg0.getId()) {
            case R.id.baskOrderUI_footballText:   // 竞彩足球
                Intent footIntent = new Intent(getContext(), FootballFragmentActivityI.class);
                startActivity(footIntent);

                break;
            case R.id.baskOrderUI_basketballText:   // 竞彩蓝球
                Intent basketIntent = new Intent(getContext(), JCLQFragmentActivityI.class);
                startActivity(basketIntent);
                break;
            case R.id.baskOrderUI_myBaskText:
                if (!MySharedPreferences.getInstance().getLoginStatus()) {
                    AppLotteryInfos.clear();
                    ViewCallBack.getInstance().countDownObjs.clear();
                    ActivityTaskManager.getInstance().closeAllActivity();
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                Intent intent = new Intent(getContext(), MyBaskOrderActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }

    @Override
    public void onRightClick() {
        Intent intent = new Intent(getContext(), RecommendHelpActivity.class);
        startActivity(intent);
    }

    @Override
    public void onLeftClick() {

    }

    /**
     * 晒单个人详情查询
     *
     * @param showProgress
     */
    private void findRecommendedUserDetail(boolean showProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("type", type);    // 类型（晒单：0；跟单：1）
            request_json.put("startLine", page);
            request_json.put("maxLine", count);
            httpPostJson(CommandUtil.FINDRECOMMENDEDUSERDETAIL, Commands.FINDRECOMMENDEDUSERDETAIL, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 个人晒单或跟单查询
     *
     * @param showProgress
     */
    private void findRecommendedUserOrders(boolean showProgress) {
        JSONObject request_json = new JSONObject();
        try {
            request_json.put("type", type);    // 类型（晒单：0；跟单：1）
            request_json.put("startLine", page);
            request_json.put("maxLine", count);
            httpPostJson(CommandUtil.FINDRECOMMENDEDUSERORDERS, Commands.FINDRECOMMENDEDUSERORDERS, request_json,
                    showProgress);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onSuccess(int requestCode, StringResultBean resultBean, String result) {
        super.onSuccess(requestCode, resultBean, result);
        switch (requestCode) {
            case CommandUtil.FINDRECOMMENDEDUSERDETAIL:
                MyRecommendBean userInfor = JSON.parseObject(resultBean.getData(), MyRecommendBean.class);
                MyRecommendOrderBean orderBean = new MyRecommendOrderBean();
                orderBean.setItem("head");
                orderBean.setUserBean(userInfor);
                infos.add(0, orderBean);
                adapter.setInfos(infos, type);
                break;
            case CommandUtil.FINDRECOMMENDEDUSERORDERS:
                List<MyRecommendOrderBean> beans = JSON.parseArray(resultBean.getData(), MyRecommendOrderBean.class);
                isFirst = false;
                if (page == 0) {
                    infos.clear();
                    infos.addAll(beans);
                    mRefreshLayout.finishRefresh();
                    if (beans.isEmpty()) {
                        adapter.setInfos(false);
                    } else {
                        adapter.setInfos(true);
                    }
                    findRecommendedUserDetail(false);
                } else {
                    if (beans == null || beans.size() == 0) {
                        adapter.setInfos(false);
                    } else {
                        infos.addAll(beans);
                        adapter.setInfos(true);
                    }
                }

                break;
        }
    }

    @Override
    public void onFailure(int requestCode, String errorCode, String message) {
        if (errorCode.equals("900003")) { // 数据为空
            mRefreshLayout.finishRefresh();
            adapter.setInfos(false);
        }else {
            mRefreshLayout.finishRefresh();
            adapter.setInfos(false);
            super.onFailure(requestCode, message);
        }

    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        isFirst = true;
        page = 0;
        findRecommendedUserOrders(false);
    }

    @Override
    public void onLoadMore() {
        if (!isFirst){
            page += infos.size();
            findRecommendedUserOrders(false);
        }
    }
}
